<template>
  <div>
    <div class="  text-slate-400 ">【热度排行】</div>
    <div ref="target" class="w-full h-full"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import * as echarts from "echarts";

const props = defineProps({
  data: Array,
});
// console.log("props:", props);
let chart = null;
const target = ref(null);

onMounted(() => {
  chart = echarts.init(target.value);
  ChartInit(); // 将 chart 传递给 ChartInit 函数
});

const ChartInit = () => {
  if (!props.data || props.data.length === 0) {
    console.log("No data to display");
    return;
  }
  // 按 number_of_reviews 降序排序并提取前六个数据项
  const sortedData = props.data
    .sort((a, b) => b.number_of_reviews - a.number_of_reviews)
    .slice(0, 6);

  // 提取排序后的数据
  const yAxisData = sortedData.map(item => item.title);
  const seriesData = sortedData.map(item => item.number_of_reviews);


  const option = {
    xAxis: {
      type: "value",
      show: false,
      max: function (value) {
        return parseInt(value.max * 1.2);
      },
    },
    yAxis: {
      type: "category",
      data: yAxisData,
      inverse: true,
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#9eb1c8",
        align: 'legt',
        margin: 100,
      },
    },
    grid: {
      top: 0,
      right: 30,
      bottom: 0,
      left: -70,
      containLabel: true,
    },
    series: [
      {
        type: "bar",
        data: seriesData ,
        showBackground: true,
        backgroundStyle: {
          color: "rgba(180,180,180,0.2)",
        },
        itemStyle: {
          color: "#5D98CE",
          borderRadius: 5,
          shadowColor: "rgba(0, 0, 0, 0.3)",
          shadowBlur: 5,
        },
        barWidth: 6,
        label: {
          show: true,
          position: "right",
          color: "#fff",
        },
      },
    ],
  };
  chart.setOption(option);
};
watch(() => props.data, ChartInit);
</script>

<style lang="scss" scoped></style>
